package com.jt.www.util;

import com.jt.www.exception.ServiceException;

import java.rmi.ServerException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class DateUtils {

    /**
     * 日期格式，年份，例如：04，08
     */
    public static final String DATE_FORMAT_YY = "yy";
    /**
     * 日期格式，年份，例如：2004，2008
     */
    public static final String DATE_FORMAT_YYYY = "yyyy";
    /**
     * 日期格式，年份和月份，例如：200707，200808
     */
    public static final String DATE_FORMAT_YYYYMM = "yyyyMM";
    /**
     * 日期格式，年份和月份，例如：200707，2008-08
     */
    public static final String DATE_FORMAT_YYYY_MM = "yyyy-MM";
    /**
     * 日期格式，年月日，例如：050630，080808
     */
    public static final String DATE_FORMAT_YYMMDD = "yyMMdd";
    /**
     * 日期格式，年月日，用横杠分开，例如：06-12-25，08-08-08
     */
    public static final String DATE_FORMAT_YY_MM_DD = "yy-MM-dd";
    /**
     * 日期格式，年月日，例如：20050630，20080808
     */
    public static final String DATE_FORMAT_YYYYMMDD = "yyyyMMdd";
    /**
     * 日期格式，年月日，用横杠分开，例如：2006-12-25，2008-08-08
     */
    public static final String DATE_FORMAT_YYYY_MM_DD = "yyyy-MM-dd";
    /**
     * 日期格式，年月日，例如：2016.10.05
     */
    public static final String DATE_FORMAT_POINTYYYYMMDD = "yyyy.MM.dd";
    /**
     * 日期格式，年月日，例如：2016/10/05
     */
    public static final String DATE_FORMAT_SPRITYYYYMMDD = "yyyy/MM/dd";
    /**
     * 日期格式，年月日，例如：2016年10月05日
     */
    public static final String DATE_TIME_FORMAT_YYYY年MM月DD日 = "yyyy年MM月dd日";
    /**
     * 日期格式，年月日时分，例如：200506301210，200808081210
     */
    public static final String DATE_FORMAT_YYYYMMDDHHmm = "yyyyMMddHHmm";
    /**
     * 日期格式，年月日时分，例如：20001230 12:00，20080808 20:08
     */
    public static final String DATE_TIME_FORMAT_YYYYMMDD_HH_MI = "yyyyMMdd HH:mm";
    /**
     * 日期格式，年月日时分，例如：2000-12-30 12:00，2008-08-08 20:08
     */
    public static final String DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI = "yyyy-MM-dd HH:mm";
    /**
     * 日期格式，年月日时分秒，例如：20001230120000，20080808200808
     */
    public static final String DATE_TIME_FORMAT_YYYYMMDDHHMISS = "yyyyMMddHHmmss";
    /**
     * 日期格式，年月日时分秒，年月日用横杠分开，时分秒用冒号分开      * 例如：2005-05-10 23：20：00，2008-08-08 20:08:08
     */
    // ==格式到年月日 时分秒 毫秒==
    public static final String DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS = "yyyy-MM-dd HH:mm:ss";
    /**
     * 日期格式，年月日时分秒毫秒，例如：20001230120000123，20080808200808456
     */
    public static final String DATE_TIME_FORMAT_YYYYMMDDHHMISSSSS = "yyyyMMddHHmmssSSS";
    public static final String DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS_SSS = "yyyy-MM-dd HH:mm:ss.SSS";
    /**
     * 日期格式，月日时分，例如：10-05 12:00
     */
    public static final String DATE_FORMAT_MMDDHHMI = "MM-dd HH:mm";
    public static final String DATE_FORMAT_HHMI = "HH:mm";
    public static final String DATE_FORMAT_HH_MM_SS = "HH:mm:ss";
    public static final SimpleDateFormat format = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
    public static final SimpleDateFormat format_date_format_yy = new SimpleDateFormat(DATE_FORMAT_YY);
    public static final SimpleDateFormat format_date_format_yymmdd = new SimpleDateFormat(DATE_FORMAT_YYMMDD);
    public static final SimpleDateFormat format_date_format_yyyymmdd = new SimpleDateFormat(DATE_FORMAT_YYYYMMDD);
    public static final SimpleDateFormat format_date_format_yyyy_mm_dd = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD);
    public static final SimpleDateFormat format_date_format_sprityyyymmdd = new SimpleDateFormat(DATE_FORMAT_SPRITYYYYMMDD);
    public static final String DATE_FORMAT_YYYYMMDDHHMM = "yyyy/MM/dd HH:mm";
    private static final String TIMEHEADER = "数据更新于";
    private static final String TIMEENDHOUR = "小时前";
    private static final String TIMEENDMIN = "分钟前";
    private static final String TIMEENDDATE = "天前";
    private static final long DAYUNIT = 1000 * 60 * 60 * 24;
    private static final long HOURUNIT = 1000 * 60 * 60;
    private static final long MINUNIT = 1000 * 60;
    static SimpleDateFormat df = (SimpleDateFormat) DateFormat.getDateInstance();
    static String[] patterns =
            {DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS, DATE_FORMAT_YY_MM_DD, DATE_FORMAT_MMDDHHMI, DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS, DATE_FORMAT_YYYYMMDDHHMM, DATE_FORMAT_HH_MM_SS
            };
    static ZoneId ZONEID_BJ = ZoneId.of("GMT+08:00");

    public static String todayStr() {
        Date now = new Date();
        return format_date_format_yyyymmdd.format(now);
    }

    public static String todaySixStr() {
        Date now = new Date();
        return format_date_format_yymmdd.format(now);
    }

    public static String todayTwoStr() {
        Date now = new Date();
        return format_date_format_yy.format(now);
    }

    public static String toYmdHms(Date now) {
        SimpleDateFormat format_date_format_yyyy_mm_dd_hh_mm_ss = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        return format_date_format_yyyy_mm_dd_hh_mm_ss.format(now);
    }

    /**
     * 拼接首页数据的提示
     *
     * @param time 数据更新的时间
     * @return
     */
    public static String getTimeDistanceHour(Long time) {
        TimeZone.setDefault(TimeZone.getTimeZone("GMT+8"));
        Calendar calendarNow = Calendar.getInstance();
        StringBuilder result = new StringBuilder(TIMEHEADER);
        long endTime = calendarNow.getTime().getTime();
        //先算出两时间的毫秒数之差大于一天的天数
        int betweenDays = (int) ((endTime - time) / DAYUNIT);
        if (betweenDays > 0) {
            return result.append(betweenDays).append(TIMEENDDATE).toString();
        }
        //如果是在一天之内则用小时来表示
        int betweenHours = (int) ((endTime - time) / HOURUNIT);
        if (betweenHours > 0) {
            return result.append(betweenHours).append(TIMEENDHOUR).toString();
        }
        int betweenMin = (int) ((endTime - time) / MINUNIT);
        if (betweenMin <= 0) {
            return result.append(1).append(TIMEENDMIN).toString();
        }
        return result.append(betweenMin).append(TIMEENDMIN).toString();
    }

    /**
     * 获取某周得第一天
     *
     * @param year 年
     * @param week 周
     * @return
     */
    public static Date getFirstDayOfWeek(int year, int week) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.WEEK_OF_YEAR, week);
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek());
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        return c.getTime();
    }

    /**
     * 获取某周得最后一天
     *
     * @param year 年
     * @param week 周
     * @return
     */
    public static Date getLastDayOfWeek(int year, int week) {
        Calendar c = new GregorianCalendar();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.WEEK_OF_YEAR, week);
        c.setFirstDayOfWeek(Calendar.MONDAY);
        c.set(Calendar.DAY_OF_WEEK, c.getFirstDayOfWeek() + 6);
        c.set(Calendar.HOUR, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }

    /**
     * 获取某月得第一天
     *
     * @param year  年
     * @param month 月
     * @return
     */
    public static Date getFirstDayOfMonth(int year, int month) {
        Calendar c = Calendar.getInstance();
        c.set(year, month, 1);
        c.set(Calendar.HOUR_OF_DAY, 0);
        c.set(Calendar.MINUTE, 0);
        c.set(Calendar.SECOND, 0);
        c.set(Calendar.MILLISECOND, 0);
        return c.getTime();
    }

    /**
     * 获取某月得最后一天
     *
     * @param year  年
     * @param month 月
     * @return
     */
    public static Date getLastDayOfMonth(int year, int month) {
        Calendar c = new GregorianCalendar();
        c.set(year, month, 1);
        c.roll(Calendar.DATE, -1);
        c.set(Calendar.HOUR_OF_DAY, 23);
        c.set(Calendar.MINUTE, 59);
        c.set(Calendar.SECOND, 59);
        return c.getTime();
    }

    /**
     * 获取某季度得第一天
     *
     * @param year    　年
     * @param quarter 　季度
     * @return
     */
    public static Date getFirstDayOfQuarter(int year, int quarter) {
        Calendar c = new GregorianCalendar();

        int month = 0;
        switch (quarter) {
            case 1:
                month = 1 - 1;
                break;
            case 2:
                month = 4 - 1;
                break;
            case 3:
                month = 7 - 1;
                break;
            case 4:
                month = 10 - 1;
                break;
            default:
                month = c.get(Calendar.MONTH);
                break;
        }

        return getFirstDayOfMonth(year, month);
    }

    /**
     * 获取某季度得最一天
     *
     * @param year    　年
     * @param quarter 　季度
     * @return
     */
    public static Date getLastDayOfQuarter(int year, int quarter) {
        Calendar c = new GregorianCalendar();

        int month = 0;
        switch (quarter) {
            case 1:
                month = 3 - 1;
                break;
            case 2:
                month = 6 - 1;
                break;
            case 3:
                month = 9 - 1;
                break;
            case 4:
                month = 12 - 1;
                break;
            default:
                month = c.get(Calendar.MONTH);
                break;
        }

        return getLastDayOfMonth(year, month);
    }

    /**
     * 获取某年得第一天
     *
     * @param year 年
     * @return
     */
    public static Date getFirstDayOfYear(int year) {
        return getFirstDayOfMonth(year, 0);
    }

    /**
     * 获取某年得最后一天
     *
     * @param year 年
     * @return
     */
    public static Date getLastDayOfYear(int year) {
        return getLastDayOfMonth(year, 11);
    }

    /**
     * 是否早于当前时间
     *
     * @param date
     * @return
     */
    public static boolean isBeforeNow(Date date) {
        Calendar startTime = Calendar.getInstance();
        startTime.setTime(date);
        Calendar now = Calendar.getInstance();
        return startTime.before(now);
    }

    public static Date createBigDate() {
        Calendar startTime = Calendar.getInstance();
        startTime.set(2999, 11, 30, 0, 0, 0);
        return startTime.getTime();
    }

    public static String converDate(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_YYYY_MM_DD);
        return dateFormat.format(date);
    }
    //格式化日期，类似 202101
    public static String converDateYm(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_YYYYMM);
        return dateFormat.format(date);
    }


    public static String conver(Date date) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY年MM月DD日);
        return dateFormat.format(date);
    }

    public static String conver(Date date, String formatStr) {
        SimpleDateFormat dateFormat = new SimpleDateFormat(formatStr);
        return dateFormat.format(date);
    }

    public static Date strToDate(String str) throws ServerException {
        return strToDateIn(str, 0);
    }

    private static Date strToDateIn(String str, int index) throws ServerException {
        if (patterns.length <= (index + 1)) {
            throw new ServerException("无法解析日期格式: " + str);
        }
        String pattern = patterns[index];
        df.applyPattern(pattern);
        Date date = null;
        try {
            date = df.parse(str);
        } catch (ParseException e) {
            return strToDateIn(str, ++index);
        }
        return date;
    }

    public static Date getLastYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.YEAR, -1);
        return calendar.getTime();
    }

    //获取选择时间所在周的第一天
    public static Date getWeekFirstDay(Date date) {
        //获取到所在的周和年份
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int weeks = calendar.get(Calendar.WEEK_OF_YEAR);
        int year = calendar.get(Calendar.YEAR);
        Date firstDayOfWeek = getFirstDayOfWeek(year, weeks);
//        String format = DateUtils.format_date_format_yyyy_mm_dd.format(firstDayOfWeek);
//        System.out.println(weeks+"--------"+year+"---------------"+format+"-----"+firstDayOfWeek);
        return firstDayOfWeek;
    }

    //获取选择时间所在月的第一天
    public static Date getMouthFirstDay(Date date) {
        //获取到所在的月和年份
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int month = calendar.get(Calendar.MONTH);
        int year = calendar.get(Calendar.YEAR);
        Date firstDayOfMonth = getFirstDayOfMonth(year, month);
//        String format = DateUtils.format_date_format_yyyy_mm_dd.format(firstDayOfMonth);
//        System.out.println(month+"-----------"+year+"-------"+firstDayOfMonth+"--------"+format);
        return firstDayOfMonth;
    }

    /**
     * 日期是否在某个区间
     * @param nowTime
     * @param startTime
     * @param endTime
     * @return
     */
    public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {
        if (nowTime.getTime() == startTime.getTime()
                || nowTime.getTime() == endTime.getTime()) {
            return true;
        }
        if(startTime.getTime()<=nowTime.getTime() && endTime.getTime()>=nowTime.getTime()){
            return true;
        }else{
            return false;
        }
    }
    //获取选择时间所在年的第一天
    public static Date getYearFirstDay(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        Date firstDayOfYear = getFirstDayOfYear(year);
        calendar.setTime(firstDayOfYear);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        return firstDayOfYear;
    }

    public static Year getYear(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        return Year.of(year);
    }

    public static Date zoneToLocalTime(String dateString) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        return sdf.parse(dateString);
    }

    /**
     * 获得当前时间  liangtengfei   时分秒
     *
     * @return
     */
    public static String getCurrentTime() {
        return conver(new Date(), DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
    }

    /**
     * 获得当前时间  liangtengfei   不带时分秒
     *
     * @return
     */
    public static String getCurrentDay() {
        Date now = new Date();
        return format_date_format_yyyy_mm_dd.format(now);
    }

    /**
     * 验证字符串日期并转换成Date日期
     */
    public static Date verifyAndTransToDate(String input) throws ServerException {
        return strToDate(regularDate(input));
    }

    /**
     * 是否是日期格式字符串
     */
    public static boolean isDateFormmat(String input) {
        try {
            regularDate(input);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 是否是日期格式字符串，是则返回yyyy-MM-dd格式String日期，否则抛出异常
     *
     * @param input 字符串格式日期
     * @return yyyy-MM-dd格式日期
     */
    public static String regularDate(String input) {
        String stringDate;
        int st = 0;
        int len = input.length();
        char[] val = input.toCharArray();

        while ((st < len) && (val[st] < 48 || val[st] > 57)) {
            st++;
        }
        while ((st < len) && (val[len - 1] < 48 || val[len - 1] > 57)) {
            len--;
        }
        if ((st > 0) || (len < val.length)) {
            stringDate = input.substring(st, len);
        } else {
            stringDate = input;
        }

        boolean isPureDigit = true;
        for (char c : stringDate.toCharArray()) {
            if (c < 48 || c > 57) {
                isPureDigit = false;
                break;
            }
        }

        try {
            if (isPureDigit) {
                if (stringDate.length() == 8) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                    return String.valueOf(LocalDate.parse(stringDate, formatter));
                } else if (stringDate.length() == 6) {
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMdd");
                    return String.valueOf(LocalDate.parse(stringDate, formatter));
                } else {
                    throw new ServiceException("不能识别的日期");
                }
            } else {
                String[] ss = stringDate.split("\\D");
                Year year;
                if (ss[0].length() == 2) {
                    year = Year.parse(ss[0], DateTimeFormatter.ofPattern("yy"));
                } else if (ss[0].length() == 4) {
                    year = Year.parse(ss[0], DateTimeFormatter.ofPattern("yyyy"));
                } else {
                    throw new ServiceException("不能识别的年份");
                }
                int month = Integer.parseInt(ss[1]);
                int dayOfMonth = Integer.parseInt(ss[2]);
                return String.valueOf(LocalDate.of(year.getValue(), month, dayOfMonth));
            }
        } catch (DateTimeParseException e) {
            throw new ServiceException("不能识别的日期");
        }

    }

    /**
     * 获取系统一周前的时间
     *
     * @return
     */
    public static String getlastWeakTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.WEEK_OF_YEAR, -1);
        date = calendar.getTime();
        return df.format(date);
    }

    /**
     * 获取系统一月前的时间
     *
     * @return
     */
    public static String getlastMonthTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, -1);
        date = calendar.getTime();
        return df.format(date);
    }

    /**
     * 获取系统一周后的时间
     *
     * @return
     */
    public static String getAfterWeakTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.WEEK_OF_YEAR, 1);
        date = calendar.getTime();
        return df.format(date);
    }

    /**
     * 获取系统一月后的时间
     *
     * @return
     */
    public static String getAfterMonthTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 1);
        date = calendar.getTime();
        return df.format(date);
    }

    /**
     * 获取系统29天后的时间
     *
     * @return
     */
    public static String getAfterDayTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, 29);
        date = calendar.getTime();
        return df.format(date);
    }

    /**
     * 判断选择的日期是否是今天
     *
     * @param time
     * @return
     */
    public static boolean isToday(long time) {
        return isThisTime(time, "yyyy-MM-dd");
    }

    public static boolean isThisTime(long time, String pattern) {
        Date date = new Date(time);
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String param = sdf.format(date);//参数时间
        String now = sdf.format(new Date());//当前时间
        return param.equals(now);
    }

    /**
     * 将字符串转日期成Long类型的时间戳，格式为：yyyy-MM-dd HH:mm:ss
     */
    public static Long convertTimeToLong(String time) {
        DateTimeFormatter ftf = DateTimeFormatter.ofPattern(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
        LocalDateTime parse = LocalDateTime.parse(time, ftf);
        return LocalDateTime.from(parse).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * 获取系统3天前的时间
     *
     * @return
     */
    public static String getTreelastTime(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, -3);
        date = calendar.getTime();
        return df.format(date);
    }

    /**
     * 获取系统3天后的时间
     *
     * @return
     */
    public static String getAfterDay(String format) {
        SimpleDateFormat df = new SimpleDateFormat(format);
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_YEAR, 3);
        date = calendar.getTime();
        return df.format(date);
    }

    /**
     * 带时分秒的日期字符串转换
     *
     * @param input        输入的日期
     * @param inputFormat  输入日期的格式
     * @param outputFormat 输出日期的格式
     * @return 输出指定格式的日期，可以带时分秒，也可以不带
     */
    public static String formattedDateTime(String input, String inputFormat, String outputFormat) {
        DateTimeFormatter inputFormatter = DateTimeFormatter.ofPattern(inputFormat);
        LocalDateTime localDateTime = LocalDateTime.parse(input, inputFormatter);

        DateTimeFormatter outputFormatter = DateTimeFormatter.ofPattern(outputFormat);
        return localDateTime.format(outputFormatter);
    }

    /**
     * 计算时间差
     *
     * @param endDate
     * @param nowDate
     * @return
     */
    public static String getDatePoor(Date endDate, Date nowDate) {

        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;

        if (day > 0) {
            return day + "天";
        } else {
            if (hour > 0) {
                return hour + "小时";
            } else {
                return min + "分钟";
            }
        }
    }

    /**
     * 日期String转Date
     *
     * @param dateStr
     * @param dateFormat
     * @return java.util.Date
     * @author guohuibin
     * @date 2018/8/8 11:07
     */
    public static Date str2Date(String dateStr, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        Date date = null;
        try {
            date = sdf.parse(dateStr);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 获取两个日期相差的月数
     */
    public static int getMonthDiff(Date d1, Date d2) {
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(d1);
        c2.setTime(d2);
        int year1 = c1.get(Calendar.YEAR);
        int year2 = c2.get(Calendar.YEAR);
        int month1 = c1.get(Calendar.MONTH);
        int month2 = c2.get(Calendar.MONTH);
        int day1 = c1.get(Calendar.DAY_OF_MONTH);
        int day2 = c2.get(Calendar.DAY_OF_MONTH);
        // 获取年的差值
        int yearInterval = year1 - year2;
        // 如果 d1的 月-日 小于 d2的 月-日 那么 yearInterval-- 这样就得到了相差的年数
        if (month1 < month2 || month1 == month2 && day1 < day2) {
            yearInterval--;
        }
        // 获取月数差值
        int monthInterval = (month1 + 12) - month2;
        if (day1 < day2) {
            monthInterval--;
        }
        monthInterval %= 12;
        int monthsDiff = Math.abs(yearInterval * 12 + monthInterval);
        return monthsDiff;
    }

    public static String format(Date date, String dateFormat) {
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        String dateStr = null;
        try {
            dateStr = sdf.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dateStr;
    }

    /**
     * 日期相加
     *
     * @param date   日期
     * @param field  加减单位 Calendar 下面的常量为参数
     * @param amount
     * @return
     */
    public static Date add(Date date, int field, int amount) {
        if (null == date) {
            return null;
        }
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(field, amount);
        date = calendar.getTime();   //这个时间就是日期往后推一天的结果
        return date;
    }

    public static boolean compareDate(Date d1, Date d2) {
        try {
            return ZonedDateTime.ofInstant(d1.toInstant(), ZONEID_BJ).toLocalDate().isAfter(
                    ZonedDateTime.ofInstant(
                            d2.toInstant(), ZONEID_BJ)
                            .toLocalDate());
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 计算保险天数：根据时间秒毫秒数判断两个时间的间隔
     *
     * @param end
     * @param start
     * @return
     */
    public static int calculatedDays(String end, String start) {
        try {
            SimpleDateFormat sf = new SimpleDateFormat(DATE_TIME_FORMAT_YYYY_MM_DD_HH_MI_SS);
            Date date1 = sf.parse(end);
            Date date2 = sf.parse(start);
            return calculatedDays(date1, date2);
        } catch (ParseException e) {
            e.printStackTrace();
            return 0;
        }
    }


    /**
     * 计算保险天数：根据时间秒毫秒数判断两个时间的间隔
     *
     * @param end
     * @param start
     * @return
     */
    public static int calculatedDays(Date end, Date start) {
        double d1 = end.getTime() - start.getTime();
        double d2 = (1000 * 3600 * 24);
        Double ceil = Math.ceil(d1 / d2);
        return ceil.intValue();
    }


    /**
     * 判断两个时间是否是同一天
     *
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameDay(Date date1, Date date2) {
        SimpleDateFormat fmt = new SimpleDateFormat(DATE_FORMAT_YYYYMMDD);
        return fmt.format(date1).equals(fmt.format(date2));
    }


    /**
     * 判断两个时间是否是同一月
     *
     * @param date1
     * @param date2
     * @return
     */
    public static boolean isSameMonth(Date date1, Date date2) {
        SimpleDateFormat fmt = new SimpleDateFormat(DATE_FORMAT_YYYYMM);
        return fmt.format(date1).equals(fmt.format(date2));
    }

}
